package com.sdry.system.controller;
import	java.util.Base64;

import com.sdry.common.BaseController;
import com.sdry.common.ResultAppInfo;
import com.sdry.system.entity.RoleUser;
import com.sdry.system.entity.SysUser;
import com.sdry.system.service.RoleService;
import com.sdry.system.service.UserService;
import com.sdry.untils.JwtUtil;
import com.sdry.untils.Md5Util;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.security.provider.MD5;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

/**
 * @Description app登陆管理
 * @Author chenBin
 * @Date 2020-04-07 10:25
 * @Version 1.0
 **/
@Controller
@RequestMapping(value = "appLogin")
public class AppLoginController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;



    /**
     * 登录
     * @param userName 用户信息
     * @param password 返回
     * @return ResultAppInfo
     */
    @RequestMapping("/toLogin")
    @ResponseBody
    public Map<String,Object> login(String userName, String password, HttpServletRequest request) {
        password = Md5Util.encrypt(password);
        UsernamePasswordToken token = new UsernamePasswordToken(userName,password);
        Subject subject = SecurityUtils.getSubject();
        SysUser user1 = new SysUser();
        String tokenString = null;
        try {
            //登陆成功
            subject.login(token);
            user1 = (SysUser) subject.getPrincipal();
            //token
            tokenString = JwtUtil.sign(user1.getUsername(), user1.getPassword());
            if (tokenString != null) {
                request.getSession().setAttribute("Token",tokenString);
            }
        } catch (UnknownAccountException uae) {
            return getResultAppLogin("0",null,"账号不正确",tokenString);

        } catch (IncorrectCredentialsException ice) {
            return getResultAppLogin("0",null,"密码不正确",tokenString);

        } catch (LockedAccountException lae) {
            return getResultAppLogin("0",null,"账号被锁定",tokenString);

        } catch (AuthenticationException ae) {
            return getResultAppLogin("0",null,"登录出错",tokenString);
        }

        return  getResultAppLogin("1",user1,"",tokenString);
    }
}
